import React from 'react';
import { Alert, message, Skeleton, Spin } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import MaterialsSection from '@/pages/Organization/EmployeeManage/components/EmployeeInfoSections/MaterialsSection';
import {
    getEmployeeEntityMaterial,
    uploadEmployeeEntityMaterial,
    removeEmployeeEntityMaterial
} from '@/pages/Organization/EmployeeManage/services';

/**
 * 员工详情 - 材料附件
 */
const MaterialsTabContent = ({ employeeCode, isPersonalPage, employeeInfoData }) => {
    const employeeMaterialsRequest = useRequest(() => getEmployeeEntityMaterial({ employeeCode }), {
        cacheKey: `employee-material-${employeeCode}`,
        refreshDeps: [employeeCode],
        ...defaultFormatResult
    });

    // 上传材料
    const uploadMaterialRequest = useRequest(param => uploadEmployeeEntityMaterial(param), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                employeeMaterialsRequest.run();
                message.success('上传成功');
            } else {
                message.error(msg);
            }
        }
    });

    // 删除材料
    const removeMaterialRequest = useRequest(param => removeEmployeeEntityMaterial(param), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                employeeMaterialsRequest.run();
                message.success('删除成功');
            } else {
                message.error(msg);
            }
        }
    });

    // 错误处理
    if (employeeMaterialsRequest.error) {
        return <Alert type="error" message={employeeMaterialsRequest.error?.msg || '数据加载错误'} />;
    }

    // render
    return (
        <Skeleton loading={!employeeMaterialsRequest.data} active>
            <Spin
                spinning={
                    employeeMaterialsRequest.loading || removeMaterialRequest.loading || uploadMaterialRequest.loading
                }
            >
                <MaterialsSection
                    formData={employeeMaterialsRequest.data}
                    isPersonalPage={isPersonalPage}
                    uploadMaterialAction={uploadMaterialRequest.run}
                    removeMaterialAction={removeMaterialRequest.run}
                    employeeInfoData={employeeInfoData}
                />
            </Spin>
        </Skeleton>
    );
};

export default MaterialsTabContent;
